namespace imitateMacQQ.WebApi.Domain.utils;

public static class StreamHelp
{
    /// <summary>
    /// 流转文件
    /// </summary>
    /// <param name="stream"></param>
    /// <param name="fileName"></param>
    public static async void StreamToFile(Stream stream, string fileName)
    {
        var file = Path.Combine(Directory.GetCurrentDirectory(),
            "StaticFiles");
        fileName = file + '/' + fileName;
        Console.WriteLine(fileName);
        if (stream.Length < 1 || fileName.Length < 1)
            return;
        // 把 Stream 转换成 byte[] 
        var bytes = new byte[stream.Length];
        _ = await stream.ReadAsync(bytes);
        // 设置当前流的位置为流的开始 
        stream.Seek(0, SeekOrigin.Begin);

        // 把 byte[] 写入文件 
        await using var fs = new FileStream(fileName, FileMode.Create);
        await using var bw = new BinaryWriter(fs);
        bw.Write(bytes);
        bw.Close();
        fs.Close();
    }

    /// <summary>
    /// 文件转流
    /// </summary>
    /// <param name="fileName"></param>
    /// <returns></returns>
    public static Stream FileToStream(string fileName)
    {
        // 打开文件 
        var fileStream = new FileStream(fileName,
            FileMode.Open, FileAccess.Read, FileShare.Read);

        // 读取文件的 byte[] 
        var bytes = new byte[fileStream.Length];
        _ = fileStream.Read(bytes, 0, bytes.Length);
        fileStream.Close();

        // 把 byte[] 转换成 Stream 

        Stream stream = new MemoryStream(bytes);
        return stream;
    }
}